﻿package com.rragona.utils.genericUtils 
{
	import flash.events.EventDispatcher;
	import flash.utils.Timer;
	import flash.events.TimerEvent;
	
	
	/**
	* ...
	* @author rragona
	* 
	*/
	
	public class DelayFunction extends EventDispatcher
	{
		/****************
		 * Private Vars
		 * **************/
		
		private static var _func:Function;
		private static var _params:Array;
		
		/**
		 * Delays the given function and calls it after the designated amount of time.
		 * @param	func		(Required) The function that will be called after the timer has been complete.
		 * @param	duration	(Required) The delay in seconds.
		 * @param	params		(Optional) Parameters to pass to the function, in array format: [param1, param2, param3].
		 * @param	count		(Optional) Number of times to repeat the function. (Default is just a single call of the function.)
		 */
		
		
		public static function delay(func:Function, duration:Number, params:Array = null, count:int = 1):void
		{
			_func = func;
			_params = params;
			
			var timer:Timer = new Timer(duration * 1000, count);
			
			timer.addEventListener(TimerEvent.TIMER_COMPLETE, callFunction);
			timer.start();
		}
		
		private static function callFunction(e:TimerEvent):void
		{
			if (_params == null)
			{
				_func();
			}
			else
			{
				_func.apply(_func, _params);
			}
		}
		
	}
	
}